import React, { useState, useEffect } from 'react';
import { d_sort, NuiBt, obj_str, is_empty } from 'sui';
import { load_pos } from './cmd';
import { split_psn, get_rgb } from '../../away/cmd';

const PsnView = ({ hreturn, data, title, high, cl }) => {
    const [main, setMain] = useState();
    const [main_pos, mainPos] = useState();

    useEffect(() => {
        setMain(data.box);
        load_pos(obj_str(data, "sn"), mainPos);
    }, [data]);

    useEffect(() => {
        if (!main_pos || is_empty(data.box)) {
            return;
        }

        const ret = [];

        data.box.forEach(d => {
            if (main_pos) {
                const f = main_pos[obj_str(d, "sn")];
                d["pos"] = obj_str(f, "pos");
            }

            ret.push(d);
        });

        d_sort(ret, "pos", true);

        ret.forEach((d, i) => d["pair"] = i + 1);

        setMain(ret);
    }, [data, main_pos]);

    const getTitle = () => {
        const sn = obj_str(data, "sn");
        const cl = get_rgb(sn);

        return (
            <div className="ml-4 text-3xl rounded-lg px-4" style={{ background: `rgb(${cl[0]}, ${cl[1]}, ${cl[2]})`, color: `${cl[3]}` }}>
                {title}<span className="ml-4">{sn}</span>
            </div>
        );
    };

    const head_st = "py-1 table-cell px-12 ";
    const cell_st = "py-1 table-cell px-12 ";

    const getItem = () => {
        if (is_empty(main)) {
            return null;
        }

        return main.map(d => {
            const pos = obj_str(d, "pos");
            const sn = split_psn(obj_str(d, "sn"));

            return (
                <div className="table-row" key={sn}>
                    <div className={cell_st + "text-green-300"}>{pos}</div>
                    <div className={cell_st + "text-green-300"}>{sn}</div>
                </div>
            );
        });
    };

    return (
        <div className="w-full flex flex-col">
            <div className="mt-2 inline-flex justify-between items-center">
                {getTitle()}
                <div className="inline-flex items-center">
                    <NuiBt className="h-16 mr-8" hcmd={hreturn}>返回</NuiBt>
                </div>
            </div>
            <div style={{ height: `${high - 255}px`, width: "100%" }} className="mx-2 my-4 overflow-y-auto">
                <div className="table text-white text-3xl font-bold ml-4">
                    <div className="table-row">
                        <div className={head_st}>位置</div>
                        <div className={head_st}>编号</div>
                    </div>
                    {getItem()}
                </div>
            </div>
        </div>
    );
};

export {PsnView};
